// Package metrics exposes Prometheus metrics and HTTP instrumentation middleware.
package metrics

import (
	"net/http"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
	RequestTotal = prometheus.NewCounterVec(
		prometheus.CounterOpts{Name: "wpk_http_requests_total", Help: "Total HTTP requests"},
		[]string{"path", "method", "status"},
	)
	RequestDuration = prometheus.NewHistogramVec(
		prometheus.HistogramOpts{Name: "wpk_http_request_duration_seconds", Help: "HTTP request duration", Buckets: prometheus.DefBuckets},
		[]string{"path", "method"},
	)
)

func init() {
	prometheus.MustRegister(RequestTotal, RequestDuration)
}

// Middleware to collect metrics
func Instrument(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		rw := &statusRecorder{ResponseWriter: w, status: 200}
		next.ServeHTTP(rw, r)
		dur := time.Since(start).Seconds()
		RequestTotal.WithLabelValues(r.URL.Path, r.Method, http.StatusText(rw.status)).Inc()
		RequestDuration.WithLabelValues(r.URL.Path, r.Method).Observe(dur)
	})
}

type statusRecorder struct {
	http.ResponseWriter
	status int
}

func (s *statusRecorder) WriteHeader(code int) { s.status = code; s.ResponseWriter.WriteHeader(code) }

func Handler() http.Handler { return promhttp.Handler() }
